package com.lck.tutor.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lck.tutor.common.BaseResponse;
import com.lck.tutor.common.ErrorCode;
import com.lck.tutor.common.Result;
import com.lck.tutor.exception.BusinessException;
import com.lck.tutor.model.domain.Follow;
import com.lck.tutor.model.domain.User;
import com.lck.tutor.model.request.UserLoginRequest;
import com.lck.tutor.model.request.UserRegisterRequest;
import com.lck.tutor.service.FollowService;
import com.lck.tutor.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.lck.tutor.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author:鹿存岿
 * @date 2022/10/19 21:18
 */

@RestController
@RequestMapping(("/user"))
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private FollowService followService;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();

        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return Result.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<User> login(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        //1.参数校验
        if (userLoginRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User result = userService.userLogin(userAccount, userPassword, request);
        return Result.success(result);
    }

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        User currentUser = userService.getLoginUser(request);
        long userId = currentUser.getId();
        //todo 校验用户是否合法
        User user = userService.getById(userId);
        User result = userService.getSafetyUser(user);
        return Result.success(result);
    }

    @GetMapping("/getUserById/{id}")
    public BaseResponse<User> getUserById(@PathVariable("id") Long id){
        User user = userService.getById(id);
        if (user == null){
            return Result.fail(ErrorCode.NULL_ERROR,"没有该用户");
        }
        User safetyUser = userService.getSafetyUser(user);
        return Result.success(safetyUser);
    }

    @GetMapping("/recommend")
    public BaseResponse<?> recommendUser(long pageNum,long pageSize){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        Page<User> userPage = userService.page(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(userPage);
    }

    @GetMapping("/follow")
    public BaseResponse<List<User>> follow(HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        //查询我关注的用户
        List<Follow> followList = followService.query().eq("userId", loginUser.getId()).list();
        //解析用户列表取出关注用户的id
        List<Long> followIdList = followList.stream().map(Follow::getUserFollowId).collect(Collectors.toList());
        //根据id查询出我关注的用户
        List<User> userList = userService
                .query()
                .in("id", followIdList)
                .list()
                .stream()
                .map(user->userService.getSafetyUser(user))
                .collect(Collectors.toList());
        return Result.success(userList);
    }

    @GetMapping("/followMe")
    public BaseResponse<List<User>> followMe(HttpServletRequest request){
        User loginUser = userService.getLoginUser(request);
        //查询关注我的用户
        List<Follow> followMeList = followService.query().eq("userFollowId", loginUser.getId()).list();
        //解析用户列表取出关注用户的id
        List<Long> followMeIdList = followMeList.stream().map(Follow::getUserId).collect(Collectors.toList());
        //根据id查询出关注我的用户
        List<User> userList = userService
                .query()
                .in("id", followMeIdList)
                .list()
                .stream()
                .map(user->userService.getSafetyUser(user))
                .collect(Collectors.toList());
        return Result.success(userList);
    }

    /**
     * 获取最匹配的用户
     * @param num
     * @param request
     * @return
     */
    @GetMapping("/match")
    public BaseResponse<List<User>> matchUsers(long num, long pageSize,HttpServletRequest request){
        if (num <= 0 || num > 20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        return Result.success(userService.matchUser(num,loginUser));
    }

}
